//1) 导入http模块
let http = require('http')
let https = require('https')

let url = require('url')
const cheerio = require('cheerio');//导入第三方模块cheerio

//2） 创建服务
const server = http.createServer()

server.on('request',(req,res)=>{
    const urlObj  = url.parse(req.url,true)

    res.writeHead(200,{
        //跨域 （xxx策略）
        "access-control-allow-origin":"*", //允许所有域都可以 
        "content-type":"application/json;charset=utf-8"
    })

    if(urlObj.pathname === '/api/getInfo'){
        httpget(data => res.end(spider(data)))
    } else {
        res.end('404')
    }
})

// https://i.maoyan.com/#movie
function httpget(cp){
    let data = ''
    https.get(' https://i.maoyan.com/',(res)=>{
        res.on("data",(chunk)=>{//监听response的状态，如果状态一直是data，说明还在接收数据，chunk数据片段
            data += chunk
        })
        res.on("end",()=>{//监听response的状态，如果状态是end，说明接收完成
            cp(data)
        })
    })
}

function spider(data){
    const $ = cheerio.load(data);
    let $movieList = $('.column.content')
    let movies = []
    $movieList.each((index,value)=>{
        movies.push({
            title:$(value).find('.title').text(),
            grade:$(value).find('.grade').text(),
            actor:$(value).find('.actor').text()
        })
    })
    console.log(movies)
    return JSON.stringify(movies)
}

server.listen(80,()=>{
    console.log('http://127.0.0.1')
})